/*
 * @Author: your name
 * @Date: 2021-04-17 13:50:31
 * @LastEditTime: 2021-04-17 16:33:07
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /flutter_demo/lib/pages/TakePhoto.dart
 */
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class TakePhotoPage extends StatefulWidget {
  @override
  _TakePhotoPageState createState() => _TakePhotoPageState();
}

class _TakePhotoPageState extends State<TakePhotoPage> {
  final _picker = ImagePicker();
  File _img;

  _takePhoto() async {
    PickedFile image =
        await _picker.getImage(source: ImageSource.camera, maxWidth: 400);
    setState(() {
      _img = File(image.path);
    });
  }

  _galleryPhoto() async {
    PickedFile image =
        await _picker.getImage(source: ImageSource.gallery, maxWidth: 400);
    setState(() {
      _img = File(image.path);
      // print('_img: $_img');
    });
    this._uploadPhoto(image.path);
  }

  _uploadPhoto(imgPath) async {
    print(imgPath);
    FormData formData = FormData.fromMap({
      'name': 'koa',
      'file': await MultipartFile.fromFile(imgPath, filename: 'upload.jpg')
    });

    var response =
        await Dio().post('http://jd.itying.com/imgupload', data: formData);
    print('response: $response');
  }

  Widget _buildImg() {
    if (this._img == null) {
      return Text('请选择图片');
    }
    return Image.file(this._img);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('拍照上传'),
        ),
        body: Column(
          children: <Widget>[
            ElevatedButton(onPressed: _takePhoto, child: Text('拍照')),
            ElevatedButton(onPressed: _galleryPhoto, child: Text('相册')),
            _buildImg()
          ],
        ));
  }
}
